package com.ddd.mill.infrastructure.advice;


import com.ddd.mill.infrastructure.annotation.EnumPattern;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author liu
 * @title: EnumRangePatternDateAdvice
 * @projectName user-enterprise-center
 * @date 2020/11/2314:11
 */

@Slf4j
public class EnumPatternDateAdvice implements ConstraintValidator<EnumPattern, Enum<?>> {

    // 枚举校验注解
    private EnumPattern annotation;

    @Override
    public void initialize(EnumPattern constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Enum<?> value, ConstraintValidatorContext constraintValidatorContext) {
        boolean result = false;
        Class<?> cls = annotation.target();
        if (cls.isEnum() && null != value) {
            Object[] objects = cls.getEnumConstants();
            try {
                for (Object obj : objects) {
                    if (value.equals(obj)) {
                        result = true;
                        break;
                    }
                }
            } catch (Exception e) {
                log.warn("EnumValidator call isValid() method exception.");
                result = false;
            }
        } else {
            result = true;
        }
        return result;
    }
}
